<?php
namespace Home\Controller;
use Think\Controller;
class UserController extends Controller {
    public function login(){
    	if($_POST){
    		$username = I('post.username');
	    	$pwd = I('post.password');

	    	$userModel = D('user');
	    	$userinfo = $userModel->where(array('username'=>$username))->find();
	    	if (!$userinfo) {
	    		$this->error('用户名错误','',2);
	    	}
	    	if($userinfo['password']!==md5($pwd.$userinfo['salt'])){
	    		$this->error('密码错误','',3);
	    	} else {
	    		cookie('userid',$userinfo['user_id']);
	    		cookie('username',$userinfo['username']);
	    		$this->success('恭喜你，进入爱的世界','/',2);
	    	}
    	
    	}

   	    $this->display();
    }

    public function msg(){
   	    $this->display();
    }

    public function reg(){
   	    if($_POST){
	   	    $userModel = D('User');
	   	    if(!$userModel->create()){
	   	    	echo $userModel->getError();
	   	    	exit;
		   	}
		   	$s = $this->salt();
		   	$userModel->password = md5($userModel->password.$s);
		   	$userModel->salt = $s;
	   	    $userModel->add();
	   	}
   	    $this->display();
    }

    public function salt(){
    	$str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.'!@#$%^&*()';
    	return substr(str_shuffle($str),0,8);
    }
}